#!/bin/bash
# Defaul db access:
# username: gammu-n5000
# passwd: g@mmu-n500O

#Connect to db
. dbconf.sh

# sending details
SENDTOLIST=sendto    # contains numbers we will attempt to send texts to
SENTTOLIST=sentto    # contains numbers we have attempted to send texts to
SENDMSG=sendmsg      # contains text message we want to send out
REPLYMSG=replymsg    # contains message to reply with
FAILREPLYLIST=failreply  # file contains numbers we failed to autoreply to
FAILSENDLIST=failmsg     # file contains numbers we failed to send texts to
PIDFILE=gammu.pid    # file contains the process ID of the script
echo $$ > $PIDFILE

# TIMEOUT
# how long to wait for the gammu getallsms poll before treating it as a failure
GAMMU_TIMEOUT=40

# BATCHSEND
BATCHSEND_COUNT=20 # how many texts to attempt sending to per poll
BATCHSEND_FAIL=8   # how many times to attempt sending to one number in list

while true; do
	#execute gammu command and not have output at STDOUT
	RAWDUMP=grawdump
	DATEDUMP=datedump
	SQLDUMP=sqldump
	INSERTS=inserts
	GAMMURC=/root/.gammurc

	QUERY="Select timestamp from $sms_table where phone_location='Inbox' order by timestamp desc limit 1"

	LASTTEXTDATE=`mysql -u $dbuser --password=$dbpasswd $dbname -B -s -e "$QUERY"`
#	LASTTEXTDATE="2010-04-27 10:00:00"  #debugger

	if [ "$LASTTEXTDATE" ]; then
		echo "LASTTEXTDATE at $LASTTEXTDATE"
	fi

	echo "Polling gammu..."
	if timeout $GAMMU_TIMEOUT gammu -c $GAMMURC getallsms > $RAWDUMP; then
		# turn all datestrings to mysql dates.
		./date-to-timestamp.pl $RAWDUMP > $DATEDUMP

			# turn all sms entries into mysql queries
			./gammu-to-sql.pl $DATEDUMP | ./chop-provider-spam.pl > $SQLDUMP
			# chop off all mysql queries that are earlier than LASTTEXTDATE
			if [ "$LASTTEXTDATE" ]; then
				LASTTEXTDATE=`echo $LASTTEXTDATE | cut -f 6 -d \' | sed 's/[^[:digit:]]//g'`
				./chop-dates-below.pl "$LASTTEXTDATE" $SQLDUMP > $INSERTS
				rm $SQLDUMP
			else
				mv $SQLDUMP $INSERTS
			fi

		echo `date "+%Y-%m-%d %H:%M:%S"`: Successfully polled gammu.
	else
		echo `date "+%Y-%m-%d %H:%M:%S"`: Failed to poll gammu.
		rm $INSERTS 2> /dev/null
	fi

	# If poll was successful
	if [ "`cat $INSERTS 2>/dev/null`" ] 2>/dev/null; then
		# run insert statements
		mysql -u $dbuser --password=$dbpasswd $dbname --verbose -h $dbhost < $INSERTS

		# send reply messages to each number in list
		if [ -f "$REPLYMSG" ]; then 
			for number in $(cat $INSERTS| cut -f 8 -d \'| sort | uniq); do
				echo "Replying to $number"
				fails=0
				until cat $REPLYMSG| gammu sendsms TEXT "$number"; do
					fails=$((fails+1))
					echo "Attempt number $fails"
					if [ "$fails" -ge "$BATCHSEND_FAIL" ]; then
						break;
					fi

					sleep 1
				done

			# dont try too many times on one number: send it to
			# the junk pile and move on.
			if [ "$fails" -ge "$BATCHSEND_FAIL" ]; then
				echo $number >> $FAILREPLYLIST
			fi

			echo Replied to $number `date` fails=$fails
			sleep 1
			done
		fi
	fi

	# Then send texts to the list of numbers
	if [ -f "$SENDTOLIST" ] && [ -f "$SENDMSG" ] && ! diff "$SENDTOLIST" <(cut -f 1 -d ' ' "$SENTTOLIST") -N > /dev/null; then
		# first, find the last 20 texts to send to.
		SENTLASTLINENUMBER=`diff "$SENDTOLIST" <(cut -f 1 -d ' ' "$SENTTOLIST") -N|head -n 1|cut -f 1 -d ,|sed 's/^\([[:digit:]]*\).*$/\1/'`

		# look for the next 20 numbers and attempt to send to them
		for number in `tail -n +$SENTLASTLINENUMBER "$SENDTOLIST"| head -n $BATCHSEND_COUNT`; do
			echo "Trying to send to $number"
			fails=0
			until cat $SENDMSG| gammu sendsms TEXT "$number"; do
				fails=$((fails+1))
				echo "Attempt number $fails"
				if [ "$fails" -ge "$BATCHSEND_FAIL" ]; then
					break;
				fi

				sleep 1
			done

			# dont try too many times on one number: send it to
			# the junk pile and move on.
			if [ "$fails" -ge "$BATCHSEND_FAIL" ]; then
				echo $number >> $FAILSENDLIST
			fi

			echo $number `date` fails=$fails >> $SENTTOLIST
			sleep 1
		done
	fi

	sleep 15
done
